import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  categoryListApi,
  categoryStoreApi,
  categoryUpdateApi,
  categoryDeleteApi,
  categoryShowApi,
  categorySelectApi,
  categoryUpdateStatusApi
} from "@/api/quotedPriceApi";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    name: "",
    type: 1,

  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const categoryOption = ref([
    {id: 1, name: '设备'},
    {id: 2, name: '配件'},
    {id: 3, name: '产品'},
  ])
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    {type: "expand", slot: "expand"},
    // {
    //   label: "ID",
    //   prop: "categoryId",
    //   width: 60
    // },
    {
      label: "分类名称",
      prop: "name"
    },
    // {
    //   label: "类型",
    //   prop: "type",
    //   slot: "type"
    // },
    {
      label: "状态",
      prop: "status",
      // slot: "status",
      cellRenderer: scope => (
      <el-switch
        size={scope.props.size === "small" ? "small" : "default"}
        v-model={scope.row.status}
        active-value={1}
        inactive-value={2}
        active-text="启用"
        inactive-text="禁用"
        inline-prompt
        onClick={() => switchStatus(scope as any)}
      />
      )
    },
    {
      label: "排序",
      prop: "sort"
    },
    // {
    //   label: "创建人",
    //   prop: "createUser.name"
    // },
    {
      label: "创建时间",
      prop: "createdAt"
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 120
    }
  ];
  const expandColumns: TableColumnList = [
    {
      label: "分类名称",
      prop: "name"
    },
    // {
    //   label: "类型",
    //   prop: "type",
    //   slot: "type"
    // },
    {
      label: "状态",
      prop: "status",
      // slot: "status",
      cellRenderer: scope => (
      <el-switch
        size={scope.props.size === "small" ? "small" : "default"}
        v-model={scope.row.status}
        active-value={1}
        inactive-value={2}
        active-text="启用"
        inactive-text="禁用"
        inline-prompt
        onClick={() => switchStatus(scope as any)}
      />
      )
    },
    {
      label: "排序",
      prop: "sort"
    },
    // {
    //   label: "创建人",
    //   prop: "createUser.name"
    // },
    {
      label: "创建时间",
      prop: "createdAt"
    },

    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 120
    }
  ]
  function switchStatus ({ row }) {
  	ElMessageBox.confirm(
    `确认要<strong>${
  	row.status === 2 ? "禁用" : "启用"
    }</strong><strong style='color:var(--el-color-primary)'>${
  	row.name
    }</strong>?`,
    "系统提示",
    {
  	confirmButtonText: "确定",
  	cancelButtonText: "取消",
  	type: "warning",
  	dangerouslyUseHTMLString: true,
  	draggable: true
    }
  )
    .then(async() => {
  	let params = {
  		categoryId: row.categoryId,
  		status: row.status === 2 ? 2 : 1
  	}
  	categoryUpdateStatusApi(params).then((res)=> {
  		if(res?.code === 200) {
  			onSearch()
  			message("更新状态成功!", {
  				type: "success"
  			});
  		}
  	}).catch(error => {
  	  message(error.response.data.msg ?? "操作失败,请联系管理员", {
  		type: "error"
  	  });
  	});

    })
    .catch(() => {
  	row.status === 2 ? (row.status = 1) : (row.status = 2);
    });
  }
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    let params = {
      page: form.page,
      perPage: form.perPage,
      type: form.type,
      name: form.name,
    }
    const res: any = await categoryListApi(toRaw(params));
    dataList.value = res?.result?.list;
    pagination.total = res?.result?.total*1;
    pagination.pageSize = res?.result?.perPage*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.name = "";
    form.type = 1;
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  async function openDialog(title = "创建分类", row?: FormItemProps) {

    let formInline = {
      title: title,
      categoryName: row?.name ?? null,
      categoryType: row?.categoryType ?? null,
      origin: row?.origin ?? null,
      sort: row?.sort ?? 1,
      status: row?.status ?? 1,
      type: form.type,
      categoryList: [],
      categoryId: row?.categoryId ?? null,
      parentId: row?.parentId ?? null,
      categoryOption: categoryOption.value
    };


    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            let params = {
              name: curData.categoryName,
              categoryId: curData.categoryId,
              type: curData.type,
              sort: curData.sort,
              status: curData.status,
              parentId: Array.isArray(curData.parentId) ? curData.parentId.join() : curData.parentId,
            }
            if (title === "创建分类") {
              categoryStoreApi(cleanEmptyData(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              categoryUpdateApi(cleanEmptyData(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    ElMessageBox.confirm('确定继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      categoryDeleteApi({ categoryId: row.categoryId }).then((res) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    expandColumns,
    categoryOption
  };
}
